package com.cyberscanner;

import animatefx.animation.Bounce;
import animatefx.animation.FadeIn;
import animatefx.animation.Pulse;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Glow;
import javafx.util.Duration;
import com.jfoenix.controls.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;

public class CyberScannerApp extends Application {
    private ScanTask currentTask;

    private JFXTextArea resultDisplay;
    private JFXButton scanButton;
    private JFXButton selectButton;
    private Label pathLabel;
    private TreeView<File> fileTree;
    private JFXRadioButton auditRadio;
    private JFXRadioButton webshellRadio;
    private JFXCheckBox auditJsCheckbox;
    private StatusBar statusBar;
    private JFXProgressBar progressBar;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setOnCloseRequest(event -> {
            if (currentTask != null) {
                currentTask.stop();
            }
        });
        primaryStage.setTitle("CyberMatrix - 量子安全分析引擎");
        primaryStage.setMinWidth(1280);
        primaryStage.setMinHeight(720);

        // 创建主布局
        BorderPane mainLayout = new BorderPane();
        mainLayout.getStyleClass().add("main-layout");
        mainLayout.setPrefSize(1280, 720);

        // 左侧面板
        VBox leftPanel = createLeftPanel();
        leftPanel.setMinWidth(300);
        leftPanel.setPrefWidth(300);
        leftPanel.setMaxWidth(400);
        VBox.setVgrow(fileTree, Priority.ALWAYS);
        mainLayout.setLeft(leftPanel);

        // 右侧结果显示区
        resultDisplay = new JFXTextArea();
        resultDisplay.getStyleClass().add("result-display");
        resultDisplay.setEditable(false);
        resultDisplay.setWrapText(true);
        BorderPane.setMargin(resultDisplay, new Insets(10));
        VBox.setVgrow(resultDisplay, Priority.ALWAYS);
        mainLayout.setCenter(resultDisplay);

        // 进度条
        progressBar = new JFXProgressBar();
        progressBar.setProgress(0);
        progressBar.getStyleClass().add("progress-bar");
        progressBar.setPrefWidth(Double.MAX_VALUE);

        // 状态栏
        statusBar = new StatusBar();
        statusBar.getStyleClass().add("status-bar");

        // 将进度条和状态栏放在底部
        VBox bottomBox = new VBox(5);
        bottomBox.setPadding(new Insets(5));
        bottomBox.getChildren().addAll(progressBar, statusBar);
        mainLayout.setBottom(bottomBox);

        // 场景和样式
        Scene scene = new Scene(mainLayout);
        scene.getStylesheets().add(getClass().getResource("/styles/cyber-theme.css").toExternalForm());
        
        primaryStage.setScene(scene);
        primaryStage.show();

        // 添加启动动画序列
        new FadeIn(mainLayout).play();
        new Pulse(selectButton).play();
        
        // 为pathLabel添加发光效果动画
        Glow glow = new Glow(0);
        pathLabel.setEffect(glow);
        Timeline glowTimeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(glow.levelProperty(), 0)),
            new KeyFrame(Duration.seconds(1), new KeyValue(glow.levelProperty(), 0.8)),
            new KeyFrame(Duration.seconds(2), new KeyValue(glow.levelProperty(), 0))
        );
        glowTimeline.setCycleCount(Timeline.INDEFINITE);
        glowTimeline.play();
        
        // 添加周期性动画效果
        Timeline pulseTimeline = new Timeline(
            new KeyFrame(Duration.seconds(2),
                new KeyValue(leftPanel.effectProperty(),
                    new DropShadow(10, Color.valueOf("#4d4dff"))))
        );
        pulseTimeline.setAutoReverse(true);
        pulseTimeline.setCycleCount(Timeline.INDEFINITE);
        pulseTimeline.play();
    }

    private VBox createLeftPanel() {
        VBox leftPanel = new VBox(10);
        leftPanel.getStyleClass().add("left-panel");
        leftPanel.setPadding(new Insets(10));

        // 目录选择按钮
        selectButton = new JFXButton("🌐 初始化量子扫描目标");
        selectButton.getStyleClass().add("cyber-button");
        selectButton.setOnAction(e -> selectDirectory());

        // 路径显示标签
        pathLabel = new Label("等待目标初始化...");
        pathLabel.getStyleClass().add("path-label");

        // 模式选择组
        VBox modeBox = createModeSelectionBox();

        // 文件树
        fileTree = new TreeView<>();
        fileTree.getStyleClass().add("file-tree");
        VBox.setVgrow(fileTree, Priority.ALWAYS);

        // 扫描按钮
        scanButton = new JFXButton("⚡ 启动量子安全分析");
        scanButton.getStyleClass().add("scan-button");
        scanButton.setDisable(true);
        scanButton.setOnAction(e -> startScan());

        leftPanel.getChildren().addAll(
                selectButton,
                pathLabel,
                modeBox,
                auditJsCheckbox,
                fileTree,
                scanButton
        );

        return leftPanel;
    }

    private VBox createModeSelectionBox() {
        VBox modeBox = new VBox(5);
        modeBox.getStyleClass().add("mode-box");

        Label modeLabel = new Label("🔧 分析模式");
        modeLabel.getStyleClass().add("mode-label");

        ToggleGroup modeGroup = new ToggleGroup();
        auditRadio = new JFXRadioButton("深度安全分析");
        webshellRadio = new JFXRadioButton("Webshell检测");

        auditRadio.setToggleGroup(modeGroup);
        webshellRadio.setToggleGroup(modeGroup);
        auditRadio.setSelected(true);

        auditJsCheckbox = new JFXCheckBox("包含静态资源分析");
        auditJsCheckbox.setSelected(true);

        modeBox.getChildren().addAll(modeLabel, auditRadio, webshellRadio);
        return modeBox;
    }

    private void selectDirectory() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择代码矩阵接入点");
        File selectedDirectory = directoryChooser.showDialog(null);

        if (selectedDirectory != null) {
            pathLabel.setText("📂 目标：" + selectedDirectory.getName());
            updateFileTree(selectedDirectory);
            scanButton.setDisable(false);
            statusBar.setStatus("✅ 目标初始化完成");
            
            // 添加动画效果
            new Pulse(scanButton).play();
        }
    }

    private int totalFileCount = 0;

    private void updateFileTree(File root) {
        TreeItem<File> rootItem = new TreeItem<>(root);
        rootItem.setExpanded(true);
        fileTree.setRoot(rootItem);
        totalFileCount = 0;
        populateFileTree(rootItem);

        // 设置单元格工厂来自定义显示
        fileTree.setCellFactory(tv -> new TreeCell<File>() {
            @Override
            protected void updateItem(File item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    // 只显示文件或目录名，而不是完整路径
                    setText(item.getName());
                }
            }
        });
    }

    private void populateFileTree(TreeItem<File> item) {
        File[] files = item.getValue().listFiles();
        if (files != null) {
            Arrays.sort(files, (f1, f2) -> {
                // 目录优先，然后按名称排序
                if (f1.isDirectory() && !f2.isDirectory()) {
                    return -1;
                } else if (!f1.isDirectory() && f2.isDirectory()) {
                    return 1;
                } else {
                    return f1.getName().compareToIgnoreCase(f2.getName());
                }
            });
            
            for (File file : files) {
                TreeItem<File> fileItem = new TreeItem<>(file);
                item.getChildren().add(fileItem);
                if (!file.isDirectory()) {
                    totalFileCount++;
                }
                if (file.isDirectory()) {
                    populateFileTree(fileItem);
                }
            }
        }
    }

    private void startScan() {
        if (currentTask != null) {
            currentTask.stop();
        }
        if (fileTree.getRoot() == null) {
            showAlert("警告", "请先选择代码目录！");
            return;
        }

        scanButton.setDisable(true);
        String initMsg = auditRadio.isSelected() ?
                "🚀 正在启动深度安全分析引擎..." :
                "🕵️ 正在启动Webshell检测引擎...";

        resultDisplay.setText(initMsg + "\n" + String.join("", Collections.nCopies(50, "▮")) + "\n");

        // 创建并启动扫描任务
        currentTask = new ScanTask(
                fileTree.getRoot().getValue(),
                auditRadio.isSelected(),
                auditJsCheckbox.isSelected(),
                this::updateProgress,
                this::updateStatus,
                this::showResults
        );
        new Thread(currentTask).start();
    }

    private void updateProgress(double progress) {
        javafx.application.Platform.runLater(() -> {
            progressBar.setProgress(progress);
        });
    }

    private void updateStatus(String message, javafx.scene.paint.Color color) {
        javafx.application.Platform.runLater(() -> {
            statusBar.setStatus(message);
            String style = String.format("-fx-text-fill: %s;", color.toString().replace("0x", "#"));
            Text text = new Text("⚡ " + message + "\n");
            text.setStyle(style);
            resultDisplay.appendText(text.getText());
            resultDisplay.setStyle(style);
        });
    }

    private void showResults(String report) {
        javafx.application.Platform.runLater(() -> {
            scanButton.setDisable(false);
            
            if (auditRadio.isSelected()) {
                String header = "\n📊 深度安全分析完成！统计信息：\n";
                
                // 解析报告并生成统计信息
                String[] lines = report.split("\n");
                int highRiskIssues = 0;
                int mediumRiskIssues = 0;

                for (String line : lines) {
                    if (line.contains("[高危]")) highRiskIssues++;
                    if (line.contains("[中危]")) mediumRiskIssues++;
                }

                int totalIssues = highRiskIssues + mediumRiskIssues;
                StringBuilder statisticsBuilder = new StringBuilder();
                statisticsBuilder.append(String.format(
                    "总扫描文件数：%d\n" +
                    "高危问题数：%d\n" +
                    "中危问题数：%d\n" +
                    "问题总计：%d\n",
                    totalFileCount, highRiskIssues, mediumRiskIssues, totalIssues
                ));
                
                resultDisplay.appendText(header + statisticsBuilder.toString());
            } else {
                resultDisplay.appendText("\n🎯 Webshell检测完成！");
            }
            
            statusBar.setStatus("✅ 扫描完成");

            // 添加完成动画
            new Bounce(resultDisplay).play();
        });
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}